const STORAGE_KEYS = {
    IS_LOGGED_IN: 'isLoggedIn', // 登录状态存储键
    TOKEN: 'tokenInfo',     // 认证令牌存储键
    official_service:'uid',// 人员ID
};

// 登录或重新登录请求函数
async function loginRequest(phone, password) {
    const requestData = { phone, password };
    try {
        const response = await fetch('https://crm-api.wmenzai.com/crm/accountLogin', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(requestData)
        });
        const timestamp = Date.now();
        const data = await response.json();
        if (data.code === 200) {
            chrome.storage.local.set({
                isLoggedIn: true,
                tokenInfo: {
                    token: data.data.token,
                    timestamp: timestamp  // 记录token生成的时间戳
                },
                url:data.data.avatar, //头像地址
                company:data.data.company,// 公司信息
                userName:data.data.userName,// 登录人信息
                phone: phone,
                password: password,
                uid:data.data.id,//
            }, () => {
                alert('登录成功！');
                updateUIAfterLogin();
            });
        } else {
            alert('登录失败，请重试');
        }
    } catch (error) {
        console.error('请求失败:', error);
        alert('网络错误，请重试');
    }
}

// 更新UI显示状态
async function updateUIAfterLogin() {
    const userAll = await chrome.storage.local.get(['url', 'company', 'userName']);
    document.querySelector('.container').style.display = 'none';
    document.getElementById('content-section').style.display = 'block';
    document.querySelector('div.showBox-name').textContent = userAll.userName; // 登录人赋值
    document.querySelector('div.companyName').textContent = userAll.company; // 公司赋值
    document.querySelector('.showBox-img img').src=userAll.url; // 头像赋值
    // 向内容脚本发送消息
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
        if (!tabs[0]?.url.includes('https://leads.cluerich.com/')) return;
        chrome.tabs.sendMessage(tabs[0].id, { action: "loginSuccess" });
    });
}

// 退出登录
document.getElementById('logoutBtn').addEventListener('click', () => {
    console.log('退出');
    chrome.storage.local.clear(() => {
        chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
            if (tabs[0]?.url.includes('https://leads.cluerich.com/')) {
                chrome.tabs.sendMessage(tabs[0].id, { action: "logout" });
            }
        });
        location.reload();
    });
});

// 登录操作
document.getElementById('loginBtn').addEventListener('click', () => {
    const phone = document.getElementById('phone').value;
    const password = document.getElementById('password').value;
    loginRequest(phone, password);
});

